package com.yzw.mybatisutils.controller;

import com.yzw.mybatisutils.model.DataBase;
import com.yzw.mybatisutils.model.Table;
import com.yzw.mybatisutils.service.DataBaseService;
import com.yzw.mybatisutils.service.FreemarkerService;
import com.yzw.mybatisutils.uitls.DataBaseUtil;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.File;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author：yzw
 * @Date：2017/11/28
 * @描述：
 */
@Controller
public class IndexController {
	private static final Logger LOGGER = Logger.getLogger(IndexController.class);
	private static final String MAPPER_NAME = "mapper";
	private static final String MODEL_NAME = "model";
	private static final String DAO_NAME = "dao";
	private static final String SERVICE_NAME = "service";
	private static final String CONTROLLER_NAME = "controller";

	@Value("${model.path}")
	private String modelPath;
	@Value("${xml.path}")
	private String xmlPath;
	@Value("${service.path}")
	private String servicePath;
	@Value("${controller.path}")
	private String controllerPath;


	@RequestMapping("index")
	public String index() {
		return "index";
	}

	@ResponseBody
	@RequestMapping("/source/save")
	public Map<String, Object> add(String ip, String port, String userName, String password, String dataBaseName) {
		Map<String, Object> resultMap = new HashMap<>();
		DataBase dataBase = new DataBase(ip, port, dataBaseName, "mysql", userName, password);
		List<String> dataList = DataBaseService.getTableList(dataBase);
		if (!CollectionUtils.isEmpty(dataList)) {
			resultMap.put("msg", "保存成功");
			resultMap.put("data", dataList);
			return resultMap;
		}
		resultMap.put("msg", "保存失败");
		return resultMap;
	}

	@ResponseBody
	@RequestMapping("/source/testConn")
	public Map<String, Object> testConn(String ip, String port, String userName, String password, String dataBaseName) {
		DataBase dataBase = new DataBase(ip, port, dataBaseName, "mysql", userName, password);
		Connection conn = null;
		Map<String, Object> resultMap = new HashMap<>();
		try {
			conn = DataBaseUtil.getConnection(dataBase);
			if (conn != null) {
				resultMap.put("msg", "连接成功");
				return resultMap;
			}
		} catch (Exception e) {
			LOGGER.error(e);
		} finally {
			if (conn != null) {
				try {
					conn.close();
				} catch (SQLException e) {
					LOGGER.error(e);
				}
			}
		}
		resultMap.put("msg", "连接失败");
		return resultMap;
	}

	@ResponseBody
	@RequestMapping("buildFile")
	public Map<String, List<String>> buildFile(String ip, String port, String userName, String password, String dataBaseName,
	                                           String tableName, String fileType, String packageName, String folderName) {
		Map<String, List<String>> resultMap = new HashMap<>();
		List<String> dataList = new ArrayList<>();
		DataBase dataBase = new DataBase(ip, port, dataBaseName, "mysql", userName, password);
		Table table = DataBaseService.getTableByName(tableName, dataBase);
		Map<String, Object> dataMap = DataBaseService.convertColumnType(table);
		Table table1 = (Table) dataMap.get("table");
		String filePath;
		String fileName = this.toUpperCase(DataBaseService.capColumnName(table1.getTableName()));
		//生成mapper
		if (fileType.contains(MAPPER_NAME)) {
			String path = xmlPath + folderName + System.getProperty("file.separator");
			File file = new File(path);
			if (!file.exists()) {
				file.mkdir();
			}
			filePath = path + fileName + "Mapper.xml";
			boolean result = FreemarkerService.buildMapper("MapperTemplate.ftl", packageName, filePath, table1, dataBase.getType());
			if (result) {
				dataList.add(tableName + "mapper文件生成成功");
				resultMap.put("msg", dataList);
			} else {
				dataList.add(tableName + "mapper文件生成失败");
				resultMap.put("msg", dataList);
			}
		}
		//生成dao
		if (fileType.contains(DAO_NAME)) {
			String path = modelPath + folderName + System.getProperty("file.separator") + "mapper" + System.getProperty("file.separator");
			File file = new File(path);
			if (!file.exists()) {
				file.mkdir();
			}
			filePath = path + fileName + "Mapper.java";
			boolean result = FreemarkerService.buildCommon("DaoTemplate.ftl", packageName, filePath, table1);
			if (result) {
				dataList.add(tableName + "dao文件生成成功");
				resultMap.put("msg", dataList);
			} else {
				dataList.add(tableName + "dao文件生成失败");
				resultMap.put("msg", dataList);
			}
		}
		// 生成controller
		if (fileType.contains(CONTROLLER_NAME)) {
			String path = controllerPath + folderName + System.getProperty("file.separator");
			File file = new File(path);
			if (!file.exists()) {
				file.mkdir();
			}
			filePath = path + fileName + "Controller.java";
			boolean result = FreemarkerService.buildCommon("ControllerTemplate.ftl", packageName, filePath, table1);
			if (result) {
				dataList.add(tableName + "Controller文件生成成功");
				resultMap.put("msg", dataList);
			} else {
				dataList.add(tableName + "Controller文件生成失败");
				resultMap.put("msg", dataList);
			}
		}
		//生成model
		if (fileType.contains(MODEL_NAME)) {
			String path = modelPath + folderName + System.getProperty("file.separator") + "entity" + System.getProperty("file.separator");
			File file = new File(path);
			if (!file.exists()) {
				file.mkdir();
			}
			filePath = path + fileName + ".java";
			boolean result = FreemarkerService.buildModel("ModelTemplate.ftl", packageName, filePath, table1, (List<String>) dataMap.get("packageList"));
			if (result) {
				dataList.add(tableName + "model文件生成成功");
				resultMap.put("msg", dataList);
			} else {
				dataList.add(tableName + "model文件生成失败");
				resultMap.put("msg", dataList);
			}
		}
		//生成service
		if (fileType.contains(SERVICE_NAME)) {
			//IService
//			filePath = path + fileName + "Service.java";
//			boolean result = FreemarkerService.buildCommon("IServiceTemplate.ftl", packageName, filePath, table1);
//			if (result) {
//				dataList.add("service文件生成成功");
//				resultMap.put("msg", dataList);
//			} else {
//				dataList.add("service文件生成失败");
//				resultMap.put("msg", dataList);
//			}
			//ServiceImpl
			String path = servicePath + folderName + System.getProperty("file.separator") + "impl" + System.getProperty("file.separator");
			File file = new File(path);
			if (!file.exists()) {
				file.mkdir();
			}
			filePath = path + fileName + "Service.java";
			boolean result1 = FreemarkerService.buildCommon("ServiceImplTemplate.ftl", packageName, filePath, table1);
			if (result1) {
				dataList.add(tableName + "service文件生成成功");
				resultMap.put("msg", dataList);
			} else {
				dataList.add(tableName + "service文件生成失败");
				resultMap.put("msg", dataList);
			}
		}
		return resultMap;
	}

	/**
	 * 首字母转为大写
	 *
	 * @param str
	 * @return
	 */
	private String toUpperCase(String str) {
		return str.substring(0, 1).toUpperCase() + str.substring(1);
	}
}
